<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Wxuser extends Model
{
    protected $guarded = [];
    protected $dateFormat = 'U';
    protected $casts = ['score' => 'integer'];

    public function address()
    {
        return $this->hasMany('App\Models\address');
    }

    public function scorelists()
    {
        return $this->hasMany('App\Models\Scorelist');
    }
    public function prizelists()
    {
        return $this->hasMany('App\Models\Prizelist');
    }
    public function getNicknameAttribute($val)
    {
        return base64_decode($val);
    }


    public function questionnaires()
    {
        return $this->belongsToMany('App\Models\Questionnaire', 'questionnaire_wxuser', 'wxuser_id', 'questionnaire_id');
    }

    public function addQuestionnaire($qa_id)
    {
        $this->questionnaires()->sync($qa_id);
    }
    public function reduceQuestionnaire($qa_id)
    {
        $this->questionnaires()->detach($qa_id);
    }

    public function signIn(){
        $query = Sign::where('wxuser_id',$this->id)->first();
        if($query){
            $last_time = (int)$query->last_signin_time;
            $now = time();
            $day = 1;
            if(empty($last_time)||count($last_time)<=0){
                $query->days=1;
            }else{
                if(is_yesterday($last_time)){
                    $query->days=$query->days+1;
                    $day = $query->days;
                }else{
                    $query->days=1;
                }
            }
            $query->last_signin_time=$now;
            $query->save();
            return $day;
        }else{
            Sign::create([
                'wxuser_id'=>$this->id,
                'last_signin_time'=>time(),
                'days'=>1,
                'score'=>10
            ]);
            return 1;
        }
    }
}
